import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TextInput,
  TouchableOpacity,
  Keyboard,
  FlatList,
  ActivityIndicator,
  RefreshControl
} from 'react-native';

import NavBar from '../../../components/PublicHeader';
import { Images } from '../../../public/images/images';
import { Constant } from '../../../public/js/constant';
import fetchWebApi from '../../../public/WebApi/fetchBase';
import { GET_USER_MAILLIST } from '../../../public/WebApi/mailListApi';
import getStorageValue from '../../../utils/getStorageValue';
import pinyin, { STYLE_FIRST_LETTER } from 'pinyin';
import AsyncStorage from '@react-native-community/async-storage';

export default class maillist extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sections: [],
      DATA: [],
      arr: [],
      // 首字母数组
      letterArr: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'],
      flag: true,
      newArr: [],
      result: true,
      isRefreshing: false
    };
  }

  componentDidMount = () => {
    this.getUserMaillist()
  };


  async getUserMaillist() {
    const res = await fetchWebApi(GET_USER_MAILLIST, { token: await getStorageValue(Constant.TOKEN) }, 'GET');
    console.log("########## getUserMaillist");
    console.log(res);

    if (res.status == 200) {
      this.setState({
        DATA: res.data,//.slice(0, 3)
      });
      // 根据首字母分组
      let sections2 = []
      var sections3 = []
      this.state.letterArr.map((item) => {
        sections2.push({
          title: item,
          datalist: [],
        })
      })


      // 根据首字母添加数据
      this.state.DATA.map((item, index) => {
        // 判断备注是否为空
        item.nickName = item.remarksName != null ? item.remarksName : item.nickName
        sections2.map((item2, index2) => {
          var str = pinyin(item.nickName, {
            heteronym: true,
            style: pinyin.STYLE_FIRST_LETTER
          })[0][0].toUpperCase()
          if (item2.title == str[0]) {
            // 判断名字拼音是否相同，相同push到相对应的数组下
            item2.datalist.push({
              data: item
            })
            // 判断昵称是否是以数字开头
          } else if (item2.title == '#') {
            if (item.nickName == str) {
              item2.datalist.push({
                data: item
              })
            }
          }
        })
      })

      // 判断那些字母数组里面没有数据就不显示
      sections2.map((item) => {
        if (item.datalist == '') {
        } else {
          // 首字母和分组字母一样就push到数组里面
          sections3.push({
            list: item
          })
        }
      })
      this.setState({
        sections: sections3,
      })

    } else if (res.status === 401) {
      console.log(res.status);
      await AsyncStorage.removeItem(Constant.TOKEN);
      this.props.navigation.push('Accountlogin')
    }
  }
  // 判断诚信等级
  reputation() {
    this.state.DATA.map((item, index) => {
      this.reputations(item)

    })
  }
  reputations(item) {
    return (
      parseInt(item.creditLevel) == 1 ?
        <>
          <Text style={{ color: '#FDE400' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
        </> : parseInt(item.creditLevel) == 2 ?
          <>
            <Text style={{ color: '#FDE400' }}>★</Text>
            <Text style={{ color: '#FDE400' }}>★</Text>
            <Text style={{ color: '#C4C4C4' }}>★</Text>
            <Text style={{ color: '#C4C4C4' }}>★</Text>
            <Text style={{ color: '#C4C4C4' }}>★</Text>
          </> : parseInt(item.creditLevel) == 3 ?
            <>
              <Text style={{ color: '#FDE400' }}>★</Text>
              <Text style={{ color: '#FDE400' }}>★</Text>
              <Text style={{ color: '#FDE400' }}>★</Text>
              <Text style={{ color: '#C4C4C4' }}>★</Text>
              <Text style={{ color: '#C4C4C4' }}>★</Text>
            </> : parseInt(item.creditLevel) == 4 ?
              <>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#C4C4C4' }}>★</Text>
              </> : parseInt(item.creditLevel) == 5 ?
                <>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                </> : parseInt(item.creditLevel) == 0 ?
                  <>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                  </> : null
    )
  }

  // 失去焦点关闭键盘
  onBlurHandle = () => {
    Keyboard.dismiss();
  }


  // 根据姓名搜索好友
  onChangeTexts(value) {
    var values = Array.from(value)
    if (values == "") {
      this.setState({
        flag: true,
        newArr: []
      })
    } else {
      this.state.DATA.map((item) => {
        // 把名字分成数组
        var nickName = Array.from(item.nickName)
        values.map(item2 => {
          nickName.map(items => {
            // 判断输入的值和用户姓名
            if (item2 == items) {
              this.state.arr.push(item)
              // 数组去重
              var newArr = [...new Set(this.state.arr)]
              this.setState({
                newArr: newArr
              })
              this.setState({
                result: true
              })
            } else if (this.state.arr == '') {
              this.setState({
                result: false
              })
            }
          })
        })
      })
      this.setState({
        flag: false
      })
    }
  }

  // 根据是否有备注改变名称
  remarks(item) {
    if (item.data.remarksName == null) {
      return (
        item.data.nickName
      )
    } else {
      return (
        item.data.remarksName
      )
    }
  }

  handleRefresh = () => {
    this.setState({
      isRefreshing: true,//tag,下拉刷新中，加载完全，就设置成flase
      Data: [],
    });
    this.getUserMaillist()
    this.setState({
      isRefreshing: false
    })
  }

  // space() {
  //   return (<View style={{ height: 2, width: '100%', backgroundColor: 'black' }} />)
  // }

  render() {
    const Item = ({ item }) => {
      return (
        <View>
          <View style={styles.body_fenzu}>
            <Text style={styles.fenzu_titles}>{item.list.title}</Text>
          </View>
          {
            item.list.datalist.map((item, index2) => {
              return (
                <TouchableOpacity
                  key={index2}
                  onPress={() => {
                    this.props.navigation.navigate('introduces', {
                      id: item.data.friendId,
                      refresh: () => {
                        this.getUserMaillist()
                      },
                      remarksName: item.data.nickName
                    });
                  }}>
                  <View style={styles.body_data}>
                    <View style={styles.data_view}>
                      <Image source={{ uri: item.data.avatar }} style={{ width: 47, height: 47, borderRadius: 6 }} />
                      <View>
                        <Text style={styles.data_list}>{this.remarks(item)}</Text>
                        <Text style={styles.data_list2}>
                          职业：{item.data.occupation == null ? '暂无' : item.data.occupation + ''}
                        </Text>
                      </View>
                    </View>
                    <View style={styles.pingjia}>
                      {this.reputations(item.data)}
                    </View>
                  </View>
                </TouchableOpacity>
              );
            })
          }
        </View>
      )
    }


    let newArrs = this.state.result ?
      <>
        {
          this.state.newArr.map((item, index2) => {
            return (
              <TouchableOpacity
                key={index2}
                onPress={() => {
                  this.props.navigation.navigate('introduces', {
                    params: item.flag,
                    id: item.friendId,
                    refresh: () => {
                      this.getUserMaillist()
                    },
                    remarksName: item.nickName
                  });
                }}>
                <View style={styles.body_data}>
                  <View style={styles.data_view2}>
                    <Image style={{ width: 50, height: 50, borderRadius: 6 }} source={{ uri: item.avatar }} />
                    <View>
                      <Text style={styles.data_list}>{item.nickName}</Text>
                      <Text style={styles.data_list2}>
                        职业：{item.occupation == null ? '暂无' : item.occupation + ''}
                      </Text>
                    </View>
                  </View>
                  <View style={styles.pingjia}>
                    {this.reputations(item)}
                  </View>
                </View>
              </TouchableOpacity>
            )
          })
        }
      </> :
      <>
        <View style={styles.result}>
          <Text style={styles.result_text}>未查到此用户~</Text>
        </View>
      </>
    let result = <>
      <View style={styles.result}>
        <Text style={styles.result_text}>该用户暂无好友，请添加~</Text>
      </View>
    </>
    // 显示搜索前后页面
    let lists = this.state.flag ?
      <>
        <FlatList
          // ItemSeparatorComponent={this.space}
          showsVerticalScrollIndicator={false}
          data={this.state.sections}
          renderItem={Item}
          keyExtractor={item => item.list.title}
          ListEmptyComponent={() => {
            return (
              <>{result}</>
            )
          }}
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
              colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
              progressBackgroundColor="#ffffff"
            />
          }
          initialNumToRender={6}
        />
      </> :
      <>
        {newArrs}
      </>
    // 搜索结果
    return (
      <View style={{ flex: 1 }}>
        <NavBar
          navigation={this.props.navigation}
          title={'企业好友'}
        />
        {/* 搜索框 */}
        <View style={styles.bodys_input}>
          <TextInput
            style={styles.inputs}
            inlineImageLeft="sou"
            placeholder="请输入用户名字"
            placeholderTextColor="#00000069"
            inlineImagePadding={40}
            onChange={(value) => {
              this.onChangeTexts(value.nativeEvent.text)
            }}
            onChangeText={(value) => {
              if (value == '') {
                this.setState({
                  flag: true
                })
              }
              this.setState({
                arr: []
              })
            }}
            onBlur={() => {
              this.onBlurHandle()
            }}
          />
          {/* <TouchableOpacity onPress={() => {

          }} style={styles.top_btn}>
            <Text style={styles.btn_text}>搜索</Text>
          </TouchableOpacity> */}
        </View>
        {/* 好友循环列表 */}
        {/* <ScrollView style={{ flex: 1 }}> */}
        {/* <SafeAreaView> */}
        <View style={{ flex: 1 }}>
          {lists}
        </View>
        {/* </SafeAreaView> */}
        {/* </ScrollView> */}

      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    height: 32,
    backgroundColor: 'transparent',
  },
  bodys: {
    backgroundColor: 'white',
  },
  bodys_input: {
    paddingLeft: 15,
    paddingRight: 15,
    backgroundColor: '#fff',
    paddingBottom: 10,
    // display: 'flex',
    // flexDirection: 'row',
    // justifyContent: 'space-between'
  },
  heards: {
    width: 395,
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-around',
    backgroundColor: 'white',
  },
  fontColor: {
    color: 'black',
    fontSize: 35,
  },
  inputs: {
    height: 45,
    // marginVertical: 10,
    color: 'black',
    backgroundColor: '#C4C4C440',
    borderRadius: 8,
    paddingLeft: 15,
  },
  top_btn: {
    width: 50,
    height: 45,
    backgroundColor: '#1890FF',
    borderRadius: 5,
    flexDirection: 'column',
    justifyContent: 'center'
  },
  btn_text: {
    textAlign: 'center',
    textAlignVertical: 'center',
    includeFontPadding: false,
    color: '#fff'
  },
  body_list: {
    display: 'flex',
    flexDirection: 'row',
    padding: 10,
    justifyContent: 'space-between',
    borderBottomWidth: 1,
    borderBottomColor: '#f2f2f2',
  },
  lists: {
    color: 'black',
    fontSize: 18,
  },
  body_fenzu: {
    backgroundColor: '#C4C4C424',
    paddingLeft: 10,
    padding: 5,
  },
  fenzu_titles: {
    color: 'rgba(0, 0, 0, 0.32)',
  },
  body_data: {
    display: 'flex',
    flexDirection: 'row',
    paddingLeft: 5,
    padding: 12,
    justifyContent: 'space-between',
    backgroundColor: '#fff'
  },
  data_view: {
    display: 'flex',
    flexDirection: 'row',
    marginTop: 5
  },
  data_view2: {
    display: 'flex',
    flexDirection: 'row',
  },
  data_list: {
    color: 'black',
    paddingLeft: 10,
    fontSize: 18,
  },
  data_list2: {
    color: 'black',
    paddingLeft: 10,
    fontSize: 14,
    marginVertical: 5
  },
  pingjia: {
    display: 'flex',
    flexDirection: 'row',
  },
  result: {
    padding: 30,
    flexDirection: 'column',
    justifyContent: 'center',
  },
  result_text: {
    textAlign: 'center',
    textAlignVertical: 'center',
    includeFontPadding: false,
    fontSize: 20,
    color: '#c2c2c2'
  },
  loadMore: {
    alignItems: "center"
  },
  indicator: {
    color: "red",
    margin: 10
  }
});
